package com.xsyz.reviewjwt.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xsyz.reviewjwt.pojo.User;
import com.xsyz.reviewjwt.service.UserService;
import com.xsyz.reviewjwt.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xsyz
 * @created 2020-12-30   17:54
 */
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("login")
    public Map<String, Object> login(User user) {
        Map<String, Object> map = new HashMap<>();
        log.info("用户名: [{}]", user.getName());
        log.info("密码[{}]", user.getPsw());
        try {
            //生成jwt令牌
            Map<String, String> map1 = new HashMap<>();
            map1.put("name", user.getName());
            String token = JWTUtils.getToken(map1);
            userService.find(user);
            map.put("state", true);
            map.put("msg", "认证成功");
            map.put("token", token);
        } catch (Exception e) {
            map.put("state", false);
            map.put("msg", "认证失败");
        }
        return map;
    }

    @RequestMapping("test")
    public Map<String, Object> test(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            String token = request.getHeader("token");
            DecodedJWT tokenInfo = JWTUtils.getTokenInfo(token);
            String string = tokenInfo.getClaim("name").asString();
            log.info("用户姓名:[{}]",string);
            map.put("state", true);
            map.put("msg", "认证成功");
            return map;
        }  catch (Exception e) {
            e.printStackTrace();
            map.put("msg","认证失败");
        }

        map.put("state", false);
        return map;
    }
}
